#!/usr/bin/python

# TODO This is kind of a hack but copied from dev_appserver.py.
# It looks for the AppEngine libraries by trying to find "dev_appserver.py".
# This might break on Windows.

import os
import subprocess
import sys

a = subprocess.Popen(["which", "dev_appserver.py"], stdout=subprocess.PIPE)
DEV_APPSERVER_PATH = a.communicate()[0][:-1]
DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(DEV_APPSERVER_PATH)))
SCRIPT_DIR = os.path.join(DIR_PATH, 'google', 'appengine', 'tools')

EXTRA_PATHS = [
  DIR_PATH,
  os.path.join(DIR_PATH, 'lib', 'antlr3'),
  os.path.join(DIR_PATH, 'lib', 'django'),
  os.path.join(DIR_PATH, 'lib', 'webob'),
  os.path.join(DIR_PATH, 'lib', 'yaml', 'lib'),
]

sys.path = EXTRA_PATHS + sys.path

# End appengine path setup.

import tempfile
import time
import unittest

from google.appengine.api import apiproxy_stub_map 
from google.appengine.api import datastore_file_stub 
from google.appengine.api import mail_stub 
# from google3.apphosting.api import urlfetch_stub 
# from google3.apphosting.api import user_service_stub 

APP_ID = u'test_app' 
AUTH_DOMAIN = 'gmail.com' 
LOGGED_IN_USER = 'test@example.com'  # set to '' for no logged in user
os.environ['APPLICATION_ID'] = APP_ID

class AppEngineTest(unittest.TestCase):
  """Unit test for tests that interact with the app engine and datastore.
  
  Taken from sample code from the following forum:
  http://groups.google.com/group/google-appengine/browse_thread/thread/9bf8102ae975c94c/8e222ff8c7fc7de5
  """

  def setUp(self):
    """This resets the datastore after each test runs."""

    # Ensure we're in UTC. 
    os.environ['TZ'] = 'UTC' 
    time.tzset() 

    # Start with a fresh api proxy. 
    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() 

    # Use a fresh stub datastore. 
    stub = datastore_file_stub.DatastoreFileStub(
        APP_ID, '/dev/null', '/dev/null')
    apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub) 

    # Use a fresh stub UserService. 
    # apiproxy_stub_map.apiproxy.RegisterStub( 
    #   'user', user_service_stub.UserServiceStub()) 
    os.environ['AUTH_DOMAIN'] = AUTH_DOMAIN 
    os.environ['USER_EMAIL'] = LOGGED_IN_USER 

    # Use a fresh urlfetch stub. 
    # apiproxy_stub_map.apiproxy.RegisterStub( 
    #     'urlfetch', urlfetch_stub.URLFetchServiceStub()) 

    # Use a fresh mail stub. 
    apiproxy_stub_map.apiproxy.RegisterStub(
        'mail', mail_stub.MailServiceStub())
